package com.bo.jdbc;

import java.sql.*;
import java.text.MessageFormat;

public class Main {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // 1. 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 建立数据库链接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8" +
                    "&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useSSL=false", "root", "962464wiw");
            // 3. 创建Statement对象
            statement = connection.createStatement();
            // 4. 定义SQL语句
            String sql = "select id,name,chinese,math,english,sum,class_id,School_id from student";
            // 5. 执行SQL获取结果
            resultSet = statement.executeQuery(sql);
            // 6. 遍历结果集
            while (resultSet.next()) {
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                int chinese = resultSet.getInt(3);
                int math = resultSet.getInt(4);
                int english = resultSet.getInt(5);
                int sum = resultSet.getInt(6);
                int class_id = resultSet.getInt(7);
                int School_id = resultSet.getInt(8);
                System.out.println(MessageFormat.format("学号={0},姓名={1},语文成绩={2},数学成绩={3}," +
                        "英语成绩={4},总成绩={5},班级号={6},学校号={7}", id, name, chinese, math, english, sum, class_id, School_id));
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 依次释放资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
